// pages/shop/detail/detail.ts
import { doDetail, doAddPhoneLog, doAddShareLog } from '~/api/search'
interface infoState {
  lat?: string
  lng?: string
  name?: string
  province?: string
  city?: string
  area?: string
  address?: string
}
interface phoneState {
  phone: string
  showPhone: string
}
interface cityState {
  destArea: string
  destCity: string
  destProvince: string
}
interface logisticsRouteState {
  destCity: string
  all: cityState[]
}
function getAddress(info: infoState) {
  let text = ''
  if (info?.province) {
    text += info.province
  }
  if (info?.city) {
    text += info.city
  }
  if (info?.area) {
    text += info.area
  }
  if (info?.address) {
    text += info.address
  }
  return text
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    info: {} as any,
    phones: [] as phoneState[],
    logisticsRoute: [] as logisticsRouteState[],
    isAuthSavePhoto: false,
  },
  handCallPage() {
    const { phones } = this.data
    if (phones.length === 0) {
      wx.showToast({
        title: '暂无号码',
        icon: 'none'
      })
      return
    }
    const phoneNumber = phones[0].phone
    doAddPhoneLog({
      id: this.data.info.id,
      type: 4
    })
    wx.makePhoneCall({
      phoneNumber
    })
  },
  handCall(e: any) {
    const phoneNumber = e.currentTarget.dataset.phone
    doAddPhoneLog({
      id: this.data.info.id,
      type: 4
    })
    wx.makePhoneCall({
      phoneNumber
    })
  },
  handDh() {
    const { info } = this.data
    wx.openLocation({
      latitude: info.lat,
      longitude: info.lng,
      name: info.name,
      scale: 15,
      address: getAddress(info)
    })
  },
  async init() {
    const data = await doDetail({
      id: this.data.id
    })
    if (data.destination) {
      const arr = data.destination.split('-')
      data.destinationStar = arr[0]
      data.destinationEnd = arr[1]
    } else {
      data.destinationStar = ''
      data.destinationEnd = ''
    }

    const logisticsRoute: logisticsRouteState[] = []
    data.roadLine.forEach((el: any) => {
      const index = logisticsRoute.findIndex(item => item.destCity === el.destCity)
      if (index >= 0) {
        const info = logisticsRoute[index]
        info.all.push({
          destArea: el.destArea,
          destCity: el.destCity,
          destProvince: el.destProvince
        })
      } else {
        logisticsRoute.push({
          destCity: el.destCity,
          all: [{
            destArea: el.destArea,
            destCity: el.destCity,
            destProvince: el.destProvince
          }]
        })
      }
    })

    let phones = data.mobile.split(' ').filter((el: string) => !!el)
    let newPhones: phoneState[] = []
    phones.forEach((item: string, index: number) => {
      if (item.substring(0, 1) == '短') {
        newPhones.push({
          phone: item,
          showPhone: item
        })
      } else if (item.length > 0) {
        newPhones.push({
          phone: item,
          showPhone: item.substring(0, 3) + '****' + item.substring(7)
        })
      }
    })
    this.setData({
      info: data,
      phones: newPhones,
      logisticsRoute
    })
  },
  /**
  * 保存图片
  */
  onSaveToPhone() {
    this.getSetting().then((res: any) => {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        this.authorize().then(() => {
          this.savedownloadFile(this.data.info.qrCodeUrl)
          this.setData({
            isAuthSavePhoto: false
          })
        }).catch(() => {
          wx.showToast({
            title: '您拒绝了授权',
            icon: 'none',
            duration: 1500
          })
          this.setData({
            isAuthSavePhoto: true
          })
        })
      } else {
        this.savedownloadFile(this.data.info.qrCodeUrl)
      }
    })
  },
  //打开设置，引导用户授权
  onOpenSetting() {
    wx.openSetting({
      success: (res) => {
        console.log(res.authSetting)
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.showToast({
            title: '您未授权',
            icon: 'none',
            duration: 1500
          })
          this.setData({// 拒绝授权
            isAuthSavePhoto: true
          })

        } else {// 接受授权
          this.setData({
            isAuthSavePhoto: false
          })
          this.onSaveToPhone() // 接受授权后保存图片

        }

      }
    })

  },
  // 获取用户已经授予了哪些权限
  getSetting() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: res => {
          resolve(res)
        }
      })
    })
  },
  // 发起首次授权请求
  authorize() {
    return new Promise((resolve, reject) => {
      wx.authorize({
        scope: 'scope.writePhotosAlbum',
        success: () => {
          resolve(1)
        },
        fail: res => { //这里是用户拒绝授权后的回调
          console.log('拒绝授权')
          reject()
        }
      })
    })
  },
  savedownloadFile(img: string) {
    this.downLoadFile(img).then((res: any) => {
      return this.saveImageToPhotosAlbum(res.tempFilePath)
    }).then(() => {
    })
  },
  //单文件下载(下载文件资源到本地)，客户端直接发起一个 HTTPS GET 请求，返回文件的本地临时路径。
  downLoadFile(img: string) {
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: img,
        success: (res) => {
          console.log('downloadfile', res)
          resolve(res)
        }
      })
    })
  },
  // 保存图片到系统相册
  saveImageToPhotosAlbum(saveUrl: string) {
    return new Promise((resolve, reject) => {
      wx.saveImageToPhotosAlbum({
        filePath: saveUrl,
        success: (res) => {
          wx.showToast({
            title: '保存成功',
            duration: 1000,
          })
          resolve(res)
        }
      })
    })
  },
  // 弹出模态框提示用户是否要去设置页授权
  showModal() {
    wx.showModal({
      title: '检测到您没有打开保存到相册的权限，是否前往设置打开？',
      success: (res) => {
        if (res.confirm) {
          console.log('用户点击确定')
          this.onOpenSetting() // 打开设置页面          
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e: any) {
    this.setData({
      id: e.id
    })
    this.init()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    doAddShareLog({
      id: this.data.info.id
    })
  }
})